package cn.edu.sgu.www.mhxysy.service.prop.impl;

import cn.edu.sgu.www.mhxysy.consts.CustomDirectories;
import cn.edu.sgu.www.mhxysy.consts.CustomMessages;
import cn.edu.sgu.www.mhxysy.dto.prop.PropCategoryDTO;
import cn.edu.sgu.www.mhxysy.easyui.component.impl.Tree;
import cn.edu.sgu.www.mhxysy.entity.prop.FilterCondition;
import cn.edu.sgu.www.mhxysy.entity.prop.PropCategory;
import cn.edu.sgu.www.mhxysy.entity.prop.ValueComparator;
import cn.edu.sgu.www.mhxysy.enums.PropTypes;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.mapper.prop.FilterConditionMapper;
import cn.edu.sgu.www.mhxysy.mapper.prop.PropCategoryMapper;
import cn.edu.sgu.www.mhxysy.mapper.prop.ValueComparatorMapper;
import cn.edu.sgu.www.mhxysy.redis.repository.impl.PropCategoryRepository;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import cn.edu.sgu.www.mhxysy.service.prop.PropCategoryService;
import cn.edu.sgu.www.mhxysy.util.*;
import cn.edu.sgu.www.mhxysy.vo.treegrid.PropCategoryTreeGrid;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class PropCategoryServiceImpl implements PropCategoryService {

    /**
     * 控制访问resultMap和parentMap的锁
     */
    private final ReentrantLock mapLock = new ReentrantLock();

    /**
     * 创建一个Map保存[道具类型ID => 道具类型信息]
     */
    private final Map<String, PropCategory> resultMap = new HashMap<>();

    /**
     * 创建一个Map保存[parentId => 子类型列表]
     */
    private final Map<String, List<PropCategory>> parentMap = new LinkedHashMap<>();

    private final UploadUtils uploadUtils;
    private final ImageUpdater imageUpdater;
    private final PropCategoryMapper propCategoryMapper;
    private final FilterConditionMapper filterConditionMapper;
    private final ValueComparatorMapper valueComparatorMapper;
    private final PropCategoryRepository propCategoryRepository;

    @Autowired
    public PropCategoryServiceImpl(
            UploadUtils uploadUtils,
            ImageUpdater imageUpdater,
            PropCategoryMapper propCategoryMapper,
            FilterConditionMapper filterConditionMapper,
            ValueComparatorMapper valueComparatorMapper,
            PropCategoryRepository propCategoryRepository) {
        this.uploadUtils = uploadUtils;
        this.imageUpdater = imageUpdater;
        this.propCategoryMapper = propCategoryMapper;
        this.filterConditionMapper = filterConditionMapper;
        this.valueComparatorMapper = valueComparatorMapper;
        this.propCategoryRepository = propCategoryRepository;
    }

    @Override
    public String upload(MultipartFile file) throws IOException {
        String directory = CustomDirectories.DIRECTORY_DJ;

        return uploadUtils.upload(file, directory);
    }

    @Override
    public void insert(PropCategoryDTO propCategoryDTO) {
        if (propCategoryDTO.getIsTheme() == 1) {
            ObjectUtils.requireNonNull(propCategoryDTO.getTableName(), "数据库表名" + CustomMessages.NOT_NULL);
        }

        // 保存数据到数据库
        PropCategory propCategory = toEntity(propCategoryDTO);

        propCategory.setId(null);

        if (StringUtils.isEmpty(propCategory.getParentId())) {
            propCategory.setParentId(null);
        }

        int rows = propCategoryMapper.insert(propCategory);

        if (rows > 0) {
            // 为当前分类添加子类型后设置其type为0-父类型
            String parentId = propCategory.getParentId();

            if (StringUtils.isEmpty(parentId)) {
                UpdateWrapper<PropCategory> updateWrapper = new UpdateWrapper<>();

                updateWrapper.eq("id", parentId);
                updateWrapper.eq("type", PropTypes.ZLX.getValue());

                updateWrapper.set("type", PropTypes.FLX.getValue());

                propCategoryMapper.update(updateWrapper.getEntity(), updateWrapper);
            }

            propCategoryRepository.deleteCache();
        } else {
            throw new GlobalException(ResponseCode.CONFLICT, CustomMessages.UPDATE_FAILURE);
        }
    }

    @Override
    public void deleteById(Integer id) {
        // 删除过滤条件
        QueryWrapper<FilterCondition> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("prop_id", id);

        Long count = filterConditionMapper.selectCount(queryWrapper);

        if (count > 0) {
            filterConditionMapper.delete(queryWrapper);
        }

        // 删除道具类型
        propCategoryMapper.deleteById(id);

        // 删除Redis缓存
        propCategoryRepository.deleteCache();
    }

    @Override
    public void updateById(PropCategoryDTO propCategoryDTO) {
        // 必要的数据验证
        ObjectUtils.requireNonNull(propCategoryDTO.getId(), CustomMessages.ID_NOT_NULL);

        if (propCategoryDTO.getIsTheme() == 1) {
            ObjectUtils.requireNonNull(propCategoryDTO.getTableName(), "数据库表名" + CustomMessages.NOT_NULL);
        }

        // 保存数据到数据库
        PropCategory propCategory = toEntity(propCategoryDTO);

        if (StringUtils.isEmpty(propCategory.getParentId())) {
            propCategory.setParentId(null);
        }

        propCategoryMapper.updateById(propCategory);

        propCategoryRepository.deleteCache();
    }

    @Override
    public void updateImageById(Integer id, String image) {
        imageUpdater.updateImageById(image, new Consumer<Object>() {
            @Override
            public void accept(Object o) {
                UpdateWrapper<PropCategory> updateWrapper = WrapperUtils.getUpdateWrapper(id, image);

                propCategoryMapper.update(updateWrapper.getEntity(), updateWrapper);
            }
        });
    }

    @Override
    public PropCategory selectById(Integer id) {
        return propCategoryMapper.selectById(id);
    }

    @Override
    public List<Tree<PropCategory>> listTree() {
        mapLock.lock();

        resultMap.clear();
        parentMap.clear();

        // 构建返回结果的树
        List<Tree<PropCategory>> trees = propCategoryRepository.getCacheOfTree();

        try {
            if (trees == null) {
                // 构建返回结果的树
                trees = new ArrayList<>();

                // 查询全部道具类型
                List<PropCategory> list = selectAll();

                /*
                 * 遍历查询结果，生成道具类型树
                 */
                for (PropCategory propCategory : list) {
                    String categoryId = propCategory.getId();

                    resultMap.put(categoryId, propCategory);

                    // 当前类型是父类型
                    if (PropTypes.FLX.getValue().equals(propCategory.getType())) {
                        if (!parentMap.containsKey(categoryId)) {
                            parentMap.put(categoryId, new ArrayList<>());
                        }
                    }

                    // 获取父类型ID
                    String parentId = propCategory.getParentId();

                    // 父类型ID不为空，则将其放到parenMap中
                    if (StringUtils.isNotEmpty(parentId)) {
                        if (!parentMap.containsKey(parentId)) {
                            parentMap.put(parentId, new ArrayList<>());
                        }

                        parentMap.get(parentId).add(propCategory);
                    }
                }

                Set<Map.Entry<String, List<PropCategory>>> entrySet = parentMap.entrySet();

                for (Map.Entry<String, List<PropCategory>> entry : entrySet) {
                    String parentId = entry.getKey();
                    PropCategory propCategory = resultMap.get(parentId);

                    // 构建一级树
                    if (propCategory.getDeep() == 1) {
                        Tree<PropCategory> tree = new Tree<>();

                        tree.setId(parentId);
                        tree.setState("open");
                        tree.setChecked(false);
                        tree.setText(propCategory.getName());

                        List<Tree<PropCategory>> children = new ArrayList<>();

                        // 一级的主题表直接在这里处理
                        if (propCategory.getIsTheme() == 1) {
                            StringBuilder tableName = new StringBuilder();

                            tableName.append(propCategory.getTableName());
                            tableName.append(generateWhereCause(parentId));

                            String orderBy = propCategory.getOrderBy();

                            if (StringUtils.isNotEmpty(orderBy)) {
                                tableName.append(" ");
                                tableName.append("order by");
                                tableName.append(" ");
                                tableName.append(orderBy);
                            }

                            List<PropCategory> themeTables = propCategoryMapper.selectByTableName(tableName.toString());

                            for (PropCategory table : themeTables) {
                                Tree<PropCategory> child = new Tree<>();

                                child.setId(propCategory.getTableName() + "_" + table.getId());
                                child.setState("open");
                                child.setChecked(false);
                                child.setText(table.getName());

                                children.add(child);
                            }
                        } else {
                            // 递归生成子树
                            children = generateTreeChildren(entry.getValue());
                        }

                        // 子树不为空时才设置
                        if (CollectionUtils.isNotEmpty(children)) {
                            tree.setState("closed");
                            tree.setChildren(children);
                        }

                        trees.add(tree);
                    }
                }

                propCategoryRepository.cacheTree(trees);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mapLock.unlock();
        }

        return trees;
    }

    @Override
    public List<PropCategoryTreeGrid> listTreeGrid() {
        List<PropCategoryTreeGrid> trees = propCategoryRepository.getCacheOfTreeGrid();

        if (trees == null) {
            trees = new ArrayList<>();

            // 查询全部道具类型
            List<PropCategory> list = selectAll();

            /*
             * 遍历查询结果，生成树形表格
             */
            for (PropCategory propCategory : list) {
                // 当前类型是父类型
                if (PropTypes.FLX.getValue().equals(propCategory.getType()) && propCategory.getParentId() == null) {
                    // 构建一级树
                    PropCategoryTreeGrid treeGrid = new PropCategoryTreeGrid();

                    treeGrid.setId(propCategory.getId());
                    treeGrid.setState("closed");
                    treeGrid.setPxh(propCategory.getPxh());
                    treeGrid.setName(propCategory.getName());
                    treeGrid.setNote(propCategory.getNote());
                    treeGrid.setType(propCategory.getType());
                    treeGrid.setDeep(propCategory.getDeep());
                    treeGrid.setImage(propCategory.getImage());
                    treeGrid.setIsTheme(propCategory.getIsTheme());
                    treeGrid.setOrderBy(propCategory.getOrderBy());
                    treeGrid.setParentId(propCategory.getParentId());
                    treeGrid.setTableName(propCategory.getTableName());
                    treeGrid.setSortField(propCategory.getSortField());

                    // 递归生成子树
                    List<PropCategoryTreeGrid> children = generateTreeGridChildren(propCategory.getId(), list);

                    // 子树不为空时才设置
                    if (!children.isEmpty()) {
                        treeGrid.setChildren(children);
                    } else {
                        treeGrid.setState("open");
                    }

                    trees.add(treeGrid);
                }
            }

            propCategoryRepository.cacheTreeGrid(trees);
        }

        return trees;
    }

    @Override
    public List<PropCategory> selectByType(Integer type) {
        QueryWrapper<PropCategory> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("type", type);

        return propCategoryMapper.selectList(queryWrapper);
    }

    @Override
    public List<PropCategoryTreeGrid> listComboTreeGrid() {
        mapLock.lock();

        resultMap.clear();
        parentMap.clear();

        // 构建返回结果的树
        List<PropCategoryTreeGrid> treeGrids = propCategoryRepository.getCacheOfComboTreeGrid();

        try {
            if (treeGrids == null) {
                // 构建返回结果的树
                treeGrids = new ArrayList<>();

                // 查询全部道具类型
                List<PropCategory> list = selectAll();

                /*
                 * 遍历查询结果，生成道具类型树
                 */
                for (PropCategory propCategory : list) {
                    String categoryId = propCategory.getId();

                    resultMap.put(categoryId, propCategory);

                    // 当前类型是父类型
                    if (PropTypes.FLX.getValue().equals(propCategory.getType()) && !parentMap.containsKey(categoryId)) {
                        parentMap.put(categoryId, new ArrayList<>());
                    }

                    // 获取父类型ID
                    String parentId = propCategory.getParentId();

                    // 父类型ID不为空，则将其放到parenMap中
                    if (StringUtils.isNotEmpty(parentId)) {
                        if (!parentMap.containsKey(parentId)) {
                            parentMap.put(parentId, new ArrayList<>());
                        }

                        parentMap.get(parentId).add(propCategory);
                    }
                }

                Set<Map.Entry<String, List<PropCategory>>> entrySet = parentMap.entrySet();

                for (Map.Entry<String, List<PropCategory>> entry : entrySet) {
                    String parentId = entry.getKey();
                    PropCategory propCategory = resultMap.get(parentId);

                    // 构建一级树
                    if (propCategory.getDeep() == 1) {
                        PropCategoryTreeGrid treeGrid = new PropCategoryTreeGrid();

                        treeGrid.setId(parentId);
                        treeGrid.setState("open");
                        treeGrid.setName(propCategory.getName());
                        treeGrid.setNote(propCategory.getNote());
                        treeGrid.setImage(propCategory.getImage());

                        List<PropCategoryTreeGrid> children = new ArrayList<>();

                        // 一级的主题表直接在这里处理
                        if (propCategory.getIsTheme() == 1) {
                            StringBuilder tableName = new StringBuilder();

                            tableName.append(propCategory.getTableName());
                            tableName.append(generateWhereCause(parentId));

                            String orderBy = propCategory.getOrderBy();

                            if (StringUtils.isNotEmpty(orderBy)) {
                                tableName.append(" ");
                                tableName.append("order by");
                                tableName.append(" ");
                                tableName.append(orderBy);
                            }

                            List<PropCategory> themeTables = propCategoryMapper.selectByTableName(tableName.toString());

                            for (PropCategory table : themeTables) {
                                PropCategoryTreeGrid child = new PropCategoryTreeGrid();

                                child.setId(propCategory.getTableName() + "_" + table.getId());
                                child.setState("open");
                                child.setName(table.getName());
                                child.setNote(table.getNote());
                                child.setImage(table.getImage());

                                children.add(child);
                            }
                        } else {
                            // 递归生成子树
                            children = generateComboTreeGridChildren(entry.getValue());
                        }

                        // 子树不为空时才设置
                        if (CollectionUtils.isNotEmpty(children)) {
                            treeGrid.setState("closed");
                            treeGrid.setChildren(children);
                        }

                        treeGrids.add(treeGrid);
                    }
                }

                propCategoryRepository.cacheComboTreeGrid(treeGrids);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mapLock.unlock();
        }

        return treeGrids;
    }

    @Override
    public List<PropCategory> selectThemes(Integer propId) {
        if (propId == null) {
            return new ArrayList<>();
        }

        QueryWrapper<PropCategory> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("is_theme", 1);
        queryWrapper.eq("id", propId);

        return propCategoryMapper.selectList(queryWrapper);
    }

    /**
     * 查询全部道具分类
     * @return List<PropCategory>
     */
    private List<PropCategory> selectAll() {
        // 创建查询条件构造器
        QueryWrapper<PropCategory> queryWrapper = new QueryWrapper<>();

        queryWrapper.orderByAsc("pxh");

        return propCategoryMapper.selectList(queryWrapper);
    }

    /**
     * 通过主题表过滤条件生成where语句
     * @param propId 道具类型ID
     * @return StringBuilder
     */
    private StringBuilder generateWhereCause(String propId) {
        QueryWrapper<FilterCondition> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("prop_id", propId);

        List<FilterCondition> filterRules = filterConditionMapper.selectList(queryWrapper);

        StringBuilder whereCause = new StringBuilder();

        if (CollectionUtils.isNotEmpty(filterRules)) {
            whereCause.append(" where 1 = 1 ");

            // and grade >= 55
            for (FilterCondition rule : filterRules) {
                ValueComparator comparator = valueComparatorMapper.selectById(rule.getComparator());

                whereCause.append(" and ");
                whereCause.append(rule.getName());
                whereCause.append(" ");
                whereCause.append(comparator.getExpress());
                whereCause.append(" ");
                whereCause.append(rule.getValue());
            }
        }

        return whereCause;
    }

    private PropCategory toEntity(PropCategoryDTO propCategoryDTO) {
        PropCategory propCategory = new PropCategory();

        propCategory.setId(propCategoryDTO.getId());
        propCategory.setPxh(propCategoryDTO.getPxh());
        propCategory.setName(propCategoryDTO.getName());
        propCategory.setType(propCategoryDTO.getType());
        propCategory.setDeep(propCategoryDTO.getDeep());
        propCategory.setNote(propCategoryDTO.getNote());
        propCategory.setIsTheme(propCategoryDTO.getIsTheme());
        propCategory.setOrderBy(propCategoryDTO.getOrderBy());
        propCategory.setParentId(propCategoryDTO.getParentId());
        propCategory.setTableName(propCategoryDTO.getTableName());
        propCategory.setSortField(propCategoryDTO.getSortField());

        return propCategory;
    }

    /**
     * 根据子道具类型列表生成当前树节点的子树
     * @param list List<PropCategory>
     * @return List<Tree<PropCategory>>
     */
    private List<Tree<PropCategory>> generateTreeChildren(List<PropCategory> list) {
        // 构建子树
        List<Tree<PropCategory>> children = new ArrayList<>();

        for (PropCategory category : list) {
            String propId = category.getId();

            // 主题表的处理，子树从数据库表中查询
            if (category.getIsTheme() == 1) {
                String tableName = category.getTableName();

                // 构建查询的表名
                StringBuilder sb = new StringBuilder();

                sb.append(tableName);
                sb.append(generateWhereCause(propId));

                String orderBy = category.getOrderBy();

                if (StringUtils.isNotEmpty(orderBy)) {
                    sb.append(" ");
                    sb.append("order by");
                    sb.append(" ");
                    sb.append(orderBy);
                }

                List<PropCategory> themeTables = propCategoryMapper.selectByTableName(sb.toString());

                for (PropCategory themeTable : themeTables) {
                    Tree<PropCategory> propCategoryTree = new Tree<>();

                    propCategoryTree.setId(tableName + "_" + themeTable.getId());
                    propCategoryTree.setState("open");
                    propCategoryTree.setChecked(false);
                    propCategoryTree.setText(themeTable.getName());

                    // 当前道具类型为父类型
                    List<Tree<PropCategory>> generateChildren = new ArrayList<>();

                    if (parentMap.containsKey(propId)) {
                        // 获取当前主题表的子类型
                        List<PropCategory> propCategories = parentMap.get(propId);

                        if (CollectionUtils.isNotEmpty(propCategories)) {
                            // 主题表的子类型只能是一个主题表
                            PropCategory propCategory = propCategories.get(0);

                            // 主题表的处理，子树从数据库表中查询
                            if (propCategory.getIsTheme() == 1) {
                                // 构建查询的表名
                                sb = new StringBuilder();

                                sb.append(propCategory.getTableName());

                                StringBuilder whereCause = generateWhereCause(propCategory.getId());

                                sb.append(whereCause);

                                // 获取主题表的分类字段
                                String sortField = propCategory.getSortField();

                                // 分类字段不为空，新增查询条件
                                if (StringUtils.isNotEmpty(sortField)) {
                                    if (StringUtils.isNotEmpty(whereCause.toString())) {
                                        sb.append(" and ");
                                    } else {
                                        sb.append(" where ");
                                    }

                                    sb.append(sortField);
                                    sb.append(" = ");
                                    sb.append(themeTable.getId());
                                }

                                orderBy = propCategory.getOrderBy();

                                if (StringUtils.isEmpty(orderBy)) {
                                    sb.append(" ");
                                    sb.append("order by");
                                    sb.append(" ");
                                    sb.append(orderBy);
                                }

                                List<PropCategory> categories = propCategoryMapper.selectByTableName(sb.toString());

                                for (PropCategory theme : categories) {
                                    Tree<PropCategory> tree = new Tree<>();

                                    tree.setId(propCategory.getTableName() + "_" + theme.getId());
                                    tree.setState("open");
                                    tree.setChecked(false);
                                    tree.setText(theme.getName());

                                    generateChildren.add(tree);
                                }
                            }
                        }
                    }

                    // 子树不为空时才设置
                    if (CollectionUtils.isNotEmpty(generateChildren)) {
                        propCategoryTree.setChildren(generateChildren);
                        propCategoryTree.setState("closed");
                    }

                    children.add(propCategoryTree);
                }
            } else {
                Tree<PropCategory> tree = new Tree<>();

                tree.setId(propId);
                tree.setState("open");
                tree.setChecked(false);
                tree.setText(category.getName());

                // 递归获取当前节点的子树
                if (parentMap.containsKey(propId)) {
                    // 递归生成子树
                    List<Tree<PropCategory>> generateChildren = generateTreeChildren(parentMap.get(propId));

                    // 子树不为空时才设置
                    if (CollectionUtils.isNotEmpty(generateChildren)) {
                        tree.setState("closed");
                        tree.setChildren(generateChildren);
                    }
                }

                children.add(tree);
            }
        }

        return children;
    }

    /**
     * 生成当前TreeGrid节点的子树
     * @param list 子道具类型列表
     * @param propId 道具类型ID
     * @return List<PropCategoryTreeGrid>
     */
    private List<PropCategoryTreeGrid> generateTreeGridChildren(String propId, List<PropCategory> list) {
        // 构建子树
        List<PropCategoryTreeGrid> children = new ArrayList<>();

        // 遍历，寻找当前一级树的子树
        for (PropCategory category : list) {
            if (category.getParentId() != null && propId.equals(category.getParentId())) {
                PropCategoryTreeGrid child = new PropCategoryTreeGrid();

                child.setId(category.getId());
                child.setState("open");
                child.setPxh(category.getPxh());
                child.setName(category.getName());
                child.setNote(category.getNote());
                child.setType(category.getType());
                child.setDeep(category.getDeep());
                child.setImage(category.getImage());
                child.setIsTheme(category.getIsTheme());
                child.setOrderBy(category.getOrderBy());
                child.setParentId(category.getParentId());
                child.setTableName(category.getTableName());
                child.setSortField(category.getSortField());

                if (StringUtils.isNotEmpty(category.getNote())) {
                    child.setNote(category.getNote());
                }

                if (category.getIsTheme() == 1) {
                    child.setTableName(category.getTableName());
                    child.setSortField(category.getSortField());
                }

                // 递归获取当前节点的子树
                List<PropCategoryTreeGrid> generateChildren = generateTreeGridChildren(category.getId(), list);

                // 子树不为空时才设置
                if (!generateChildren.isEmpty()) {
                    child.setState("closed");
                    child.setChildren(generateChildren);
                }

                children.add(child);
            }
        }

        return children;
    }

    /**
     * 根据子道具类型列表生成当前树节点的子树
     * @param list List<PropCategory>
     * @return List<PropCategoryTreeGrid>
     */
    private List<PropCategoryTreeGrid> generateComboTreeGridChildren(List<PropCategory> list) {
        // 构建子树
        List<PropCategoryTreeGrid> children = new ArrayList<>();

        for (PropCategory category : list) {
            String propId = category.getId();

            // 主题表的处理，子树从数据库表中查询
            if (category.getIsTheme() == 1) {
                String tableName = category.getTableName();

                // 构建查询的表名
                StringBuilder sb = new StringBuilder();

                sb.append(tableName);
                sb.append(generateWhereCause(propId));

                String orderBy = category.getOrderBy();

                if (StringUtils.isNotEmpty(orderBy)) {
                    sb.append(" ");
                    sb.append("order by");
                    sb.append(" ");
                    sb.append(orderBy);
                }

                List<PropCategory> themeTables = propCategoryMapper.selectByTableName(sb.toString());

                for (PropCategory themeTable : themeTables) {
                    PropCategoryTreeGrid treeGrid = new PropCategoryTreeGrid();

                    treeGrid.setId(tableName + "_" + themeTable.getId());
                    treeGrid.setState("open");
                    treeGrid.setName(themeTable.getName());
                    treeGrid.setNote(themeTable.getNote());
                    treeGrid.setImage(themeTable.getImage());

                    // 当前道具类型为父类型
                    List<PropCategoryTreeGrid> generateChildren = new ArrayList<>();

                    if (parentMap.containsKey(propId)) {
                        // 获取当前主题表的子类型
                        List<PropCategory> propCategories = parentMap.get(propId);

                        if (CollectionUtils.isNotEmpty(propCategories)) {
                            // 主题表的子类型只能是一个主题表
                            PropCategory propCategory = propCategories.get(0);

                            // 主题表的处理，子树从数据库表中查询
                            if (propCategory.getIsTheme() == 1) {
                                // 构建查询的表名
                                sb = new StringBuilder();

                                sb.append(propCategory.getTableName());

                                StringBuilder whereCause = generateWhereCause(propCategory.getId());

                                sb.append(whereCause);

                                // 获取主题表的分类字段
                                String sortField = propCategory.getSortField();

                                // 分类字段不为空，新增查询条件
                                if (StringUtils.isNotEmpty(sortField)) {
                                    if (StringUtils.isNotEmpty(whereCause.toString())) {
                                        sb.append(" and ");
                                    } else {
                                        sb.append(" where ");
                                    }

                                    sb.append(sortField);
                                    sb.append(" = ");
                                    sb.append(themeTable.getId());
                                }

                                orderBy = propCategory.getOrderBy();

                                if (StringUtils.isEmpty(orderBy)) {
                                    sb.append(" ");
                                    sb.append("order by");
                                    sb.append(" ");
                                    sb.append(orderBy);
                                }

                                List<PropCategory> categories = propCategoryMapper.selectByTableName(sb.toString());

                                categories.forEach(new Consumer<PropCategory>() {
                                    @Override
                                    public void accept(PropCategory theme) {
                                        PropCategoryTreeGrid treeGrid = new PropCategoryTreeGrid();

                                        treeGrid.setId(propCategory.getTableName() + "_" + theme.getId());
                                        treeGrid.setState("open");
                                        treeGrid.setName(theme.getName());
                                        treeGrid.setNote(theme.getNote());
                                        treeGrid.setImage(theme.getImage());

                                        generateChildren.add(treeGrid);
                                    }
                                });
                            }
                        }
                    }

                    // 子树不为空时才设置
                    if (CollectionUtils.isNotEmpty(generateChildren)) {
                        treeGrid.setChildren(generateChildren);
                        treeGrid.setState("closed");
                    }

                    children.add(treeGrid);
                }
            } else {
                PropCategoryTreeGrid treeGrid = new PropCategoryTreeGrid();

                treeGrid.setId(propId);
                treeGrid.setState("open");
                treeGrid.setName(category.getName());
                treeGrid.setNote(category.getNote());
                treeGrid.setImage(category.getImage());

                // 递归获取当前节点的子树
                if (parentMap.containsKey(propId)) {
                    // 递归生成子树
                    List<PropCategoryTreeGrid> generateChildren = generateComboTreeGridChildren(parentMap.get(propId));

                    // 子树不为空时才设置
                    if (CollectionUtils.isNotEmpty(generateChildren)) {
                        treeGrid.setChildren(generateChildren);
                        treeGrid.setState("closed");
                    }
                }

                children.add(treeGrid);
            }
        }

        return children;
    }

}